const { readFile } = require('fs');
const path = require('path');
const util = require('util');

setImmediate(() => console.log('[阶段1.immediate] 回调1'));
setImmediate(() => console.log('[阶段1.immediate] 回调2'));
setImmediate(() => console.log('[阶段1.immediate] 回调3'));

;(async () => {
  console.log('[同步任务]')
  // await 还是 本质上的时间轮询 机制 不过 后面的 代码 要他执行完之后才继续执行
  await util.promisify(readFile)(path.join(__dirname, '../../package.json'), 'utf8'); 
  console.log('[阶段2.IO] 回调1');

  process.nextTick(() => {
    console.log('[阶段2...Tick...] 回调1')
  });
  process.nextTick(() => {
      console.log('[阶段2...Tick...] 回调2')
  });
  process.nextTick(() => {
      console.log('[阶段2...Tick...] 回调3')
  });

})();
setTimeout(() => {
    console.log('[阶段1.定时器] 回调1')
}, 0);
setTimeout(() => {
    console.log('[阶段1.定时器] 回调2')
    process.nextTick(() => {
        console.log('[...Tick...] 回调4')
    });
}, 0);
setTimeout(() => {
    console.log('[阶段1.定时器] 回调3')
}, 0);
setTimeout(() => {
    console.log('[阶段1.定时器] 回调4')
}, 0);

process.nextTick(() => {
    console.log('[...Tick...] 回调1')
});
process.nextTick(() => {
    console.log('[...Tick...] 回调2')
});
process.nextTick(() => {
    console.log('[...Tick...] 回调3')
});

Promise.resolve().then(() => {
    console.log('[Promise] 回调1');

    Promise.resolve().then(() => {
        console.log('[Promise] 回调2');
    });

    setImmediate(() => console.log('[阶段1.immediate] 回调4'));
}).then(() => {
    console.log('[Promise] 回调3');
}).then(() => {
    console.log('[Promise] 回调4');
});


/*
[同步任务]
[...Tick...] 回调1
[...Tick...] 回调2
[...Tick...] 回调3
[Promise] 回调1
[Promise] 回调2
[Promise] 回调3
[Promise] 回调4
[阶段1.定时器] 回调1
[阶段1.定时器] 回调2
[阶段1.定时器] 回调3
[阶段1.定时器] 回调4
[...Tick...] 回调4
[阶段1.immediate] 回调1
[阶段1.immediate] 回调2
[阶段1.immediate] 回调3
[阶段1.immediate] 回调4
[阶段2.IO] 回调1'       // await 
[阶段2...Tick...] 回调1
[阶段2...Tick...] 回调2
[阶段2...Tick...] 回调3

-------------------------------------
[同步任务]
[...Tick...] 回调1
[...Tick...] 回调2
[...Tick...] 回调3
[Promise] 回调1
[Promise] 回调2
[Promise] 回调3
[Promise] 回调4
[阶段1.定时器] 回调1
[阶段1.定时器] 回调2
[阶段1.定时器] 回调3
[阶段1.定时器] 回调4
[...Tick...] 回调4
[阶段1.immediate] 回调1
[阶段1.immediate] 回调2
[阶段1.immediate] 回调3
[阶段1.immediate] 回调4
[阶段2.IO] 回调1
[阶段2...Tick...] 回调1
[阶段2...Tick...] 回调2
[阶段2...Tick...] 回调3
 */
